import { computed } from 'vue'
import { grwebappWs } from './grwebapp'
import { usePrintStore } from '@/stores/print'

export const usePrinter = () => {
  const printStore = usePrintStore()

  // 使用响应式的defaultPrinter
  const selectedPrinter = computed({
    get() {
      return printStore.selectedPrinter
    },
    set(value) {
      // 清空纸张选择
      printStore.selectedParper = ''
      printStore.selectedPrinter = value
    },
  })

  // 使用响应式的printList
  const printList = computed(() => printStore.printList)

  // 使用响应式的selectedPrinter
  const selectedParper = computed({
    get() {
      return printStore.selectedParper
    },
    set(value) {
      printStore.selectedParper = value
    },
  })

  // 使用响应式的parperList
  const parperList = computed(() => printStore.parperList)

  const print = (reportText: string = '', dataText: string = '') => {
    // 获取报表模板与表格数据
    Promise.all([
      fetch(reportText).then((res) => res.text()),
      fetch(dataText).then((res) => res.text()),
    ])
      .then(([reportText, tableDataText]) => {
        grwebappWs.request(
          {
            type: 'print',
            showOptionDlg: false,
            printerName: selectedPrinter.value,
            PaperName: selectedParper.value,
          },
          reportText,
          tableDataText,
        )
      })
      .catch((err) => {
        throw new Error(err)
      })
  }

  const getPrintList = () => {
    grwebappWs.request({ type: 'fun', fun: 'Printers' }, '', '', (event: MessageEvent<string>) => {
      const data = JSON.parse(event.data) as {
        count: number
        fun: string
        printers: {
          name: string
        }[]
        type: string
      }

      // 清空 响应式数据, 并重新赋值
      printStore.printList = []
      printStore.printList = [...data.printers.map((item) => item.name)]
    })
  }

  const getPrintParperList = () => {
    if (!selectedPrinter.value) {
      console.error('请选择打印机')
      return
    }

    grwebappWs.request(
      { type: 'fun', fun: 'PrinterPapers', printer: selectedPrinter.value },
      '',
      '',
      (event: MessageEvent<string>) => {
        const data = JSON.parse(event.data) as {
          error?: string
          count: number
          fun: string
          papers: {
            name: string
          }[]
          type: string
        }

        if (data.error) {
          throw new Error(data.error)
        }

        printStore.parperList = []
        printStore.parperList = [...data.papers.map((item) => item.name)]
      },
    )
  }

  return {
    selectedPrinter,
    selectedParper,
    parperList,
    printList,
    print,
    getPrintList,
    getPrintParperList,
  }
}
